#include "../logs/nanlog.h"
#include <unistd.h>

enum class TimeGap
{
    GAP_SECOND,
    GAP_MINUTE,
    GAP_HOUR,
    GAP_DAY,
};
//落地方向：指定文件
class RollByTimeSink : public nanlog::LogSink
{
public:
    //构造时传入文件名，并打开文件，将操作句柄管理起来
    RollByTimeSink(const std::string& basename, TimeGap gap_type)
        : _basename(basename), _cur_gap(0), _gap_size(0)
    {
        switch(gap_type)
        {
            case TimeGap::GAP_SECOND: _gap_size = 1; break;
            case TimeGap::GAP_MINUTE: _gap_size = 60; break;
            case TimeGap::GAP_HOUR: _gap_size = 3600; break;
            case TimeGap::GAP_DAY: _gap_size = 3600*24; break;
        }
        _cur_gap = _gap_size == 1 ? nanlog::util::Date::now() : nanlog::util::Date::now() % _gap_size;//获取当前是第几个时间段
        std::string filename = createNewFile();
        nanlog::util::File::createDirectory(nanlog::util::File::path(filename));
        _ofs.open(filename, std::ios::binary | std::ios::app);
        assert(_ofs.is_open());
    }
    void log(const char* data, size_t len)
    {
        time_t cur = nanlog::util::Date::now();
        if((cur % _gap_size) != _cur_gap)
        {
            _ofs.close();
            std::string filename = createNewFile();
            _ofs.open(filename, std::ios::binary | std::ios::app);
            assert(_ofs.is_open());
        }
        _ofs.write(data,len);
        assert(_ofs.good());
    }
private:
    std::string createNewFile()
    {
        //获取系统时间，以时间来构造文件扩展名
        time_t t = nanlog::util::Date::now();
        struct tm lt;
        localtime_r(&t, &lt);
        std::stringstream filename;

        filename << _basename;
        filename << lt.tm_year + 1900;
        filename << lt.tm_mon + 1;
        filename << lt.tm_mday;
        filename << lt.tm_hour;
        filename << lt.tm_min;
        filename << lt.tm_sec;
        filename << ".log";
    
        return filename.str();
    }
private:
    std::string _basename;
    std::ofstream _ofs;
    size_t _cur_gap;//当前是第几个时间段
    size_t _gap_size;//时间段的大小
};


int main() {
    std::unique_ptr<nanlog::LoggerBuilder> builder(new nanlog::GlobalLoggerBuilder());
    builder->buildLoggerName("async_logger");//日志器名称
    builder->buildLoggerLevel(nanlog::LogLevel::value::DEBUG);//等级
    builder->buildFormatter("[%c][%f:%l][%p]%m%n");
    builder->buildLoggerType(nanlog::LoggerType::LOGGER_ASYNC);

    builder->buildSink<RollByTimeSink>("./logfile/roll-async-by-time", TimeGap::GAP_SECOND);
    nanlog::Logger::ptr logger = builder->build();
    size_t cur = nanlog::util::Date::now();
    while(nanlog::util::Date::now() < cur + 5)
    {
        logger->fatal("这是一条测试日志");
        usleep(1000);
    }

    return 0;
}
